package cn.yuitstyle.excel;

import cn.hutool.core.util.StrUtil;
import cn.yuitstyle.excel.exception.ExcelException;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ModelDataListener<T> extends AnalysisEventListener<T> {

    private final List<T> list = new ArrayList<>();

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        if (checkAllFieldIsNull(data)) {
            return;
        }
        ExcelImportValid.valid(data);
        list.add(data);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    /**
     * 校验目标字段是否有非空数据
     *
     * @return 全空 返回true 否则 返回 false
     */
    private boolean checkAllFieldIsNull(Object obj)  {
        if (obj == null) {
            return true;
        }
        List<Field> fields = Arrays.stream(obj.getClass().getDeclaredFields()).filter(f -> f.isAnnotationPresent(ExcelProperty.class)).collect(Collectors.toList());
        try {
            for (Field f : fields) {
                f.setAccessible(true);
                if (f.get(obj) != null || StrUtil.isNotEmpty(f.get(obj).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("导入异常", e);
            throw new ExcelException("导入异常");
        }

        return true;
    }

    public List<T> getDataList() {
        return list;
    }

}

